import { Form } from 'antd-mini/es/Form/form';

Component({
  mixins: [],
  data: {
    actionSheet: false,
    avatarUrl: '../../../../image/user.jpg',
    avatar: '',
    nickName: '',
    mobile: '',
  },
  props: {},
  onInit() {
    this.form = new Form();
  },
  didMount() {

  },
  didUpdate() { },
  didUnmount() { },
  methods: {
    handleRef(ref) {
      this.form.addItem(ref);
    },
    noLogin() {
      this.setData({
        actionSheet: false
      })
    },
    async getChooseAvatar({ detail }) {
      let { userInfo: { avatar, nickName } } = detail
      const values = await this.form.submit();
      this.form.setInitialValues({
        ...values,
        nickname: nickName
      });
      this.form.reset()
      this.setData({
        avatar:avatar,
        avatarUrl: avatar
      })
    },
    doAuthorized() {
      getApp().getOpenId().then(openId=>{
        this.setData({
          openId: openId
        })
        this.doLogin()
      })
    },
    doLogin() {
      getApp().network.post(getApp().api.appletLogin, this.data.openId).then((res) => {
        if (false === res.success) {
          this.setData({
            actionSheet: true
          })
        } else {
          getApp().util.setStorage(getApp().constant.TOKEN, res.data)
          getApp().util.showToast("登录成功！")
          getApp().verifyLogin().then(res=>{
            my.reLaunch({
              url: '/pages/index/index'
            });
          })
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    async getMobile(e) {
      const values = await this.form.submit();
      let { encryptedData, sign } = e.detail
      getApp().network.post(getApp().api.decryptingOpenData, {
        encryptedData: encryptedData,
        sign: sign
      }).then((res) => {
        console.log(res)
        if (!res.mobile) {
          getApp().util.showToast('您的支付宝未绑定手机号')
        }
        this.form.setInitialValues({
          ...values,
          mobile: res.mobile,

        });
        this.form.reset()
      })
    },
    async doRegiser() {
      const values = await this.form.submit();
      console.log(values)
      var {nickname,mobile}=values
      var {openId,avatar}=this.data
      if (!avatar) {
        getApp().util.showToast('请设置用户头像')
        return
      }
      if (!nickname) {
        getApp().util.showToast('请设置用户昵称！')
        return
      }
      if (!mobile) {
        getApp().util.showToast('请设置手机号！')
        return
      }
      console.log(1111)
      getApp().network.post(getApp().api.appletRegister, {
        openId,
        nickName:nickname,
        mobile,
        avatar
      }).then((res) => {
        getApp().util.setStorage(getApp().constant.TOKEN, res)
        getApp().util.showToast("登录成功！")
        getApp().verifyLogin().then(res=>{
          my.reLaunch({
            url: '/pages/index/index'
          });
        })
      }).catch((err) => {
        console.log(err)
      })
    }
  },
});
